package com.feng.spring51.dao;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class JDKProxy {
    public static void main(String[] args) {
        Class[] interfaces = {UserDao.class};
        /*Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        });*/
        UserDaoImpl userDao = new UserDaoImpl();
        UserDao dao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int sum = dao.sum(1, 2);
        System.out.println("sum: "+sum);
    }
}

//創建代理對象代碼
class UserDaoProxy implements InvocationHandler{

    //把創建的代理對象傳進來
    //有參數構造傳遞
    private Object obj;
    public UserDaoProxy(Object obj){
        this.obj=obj;
    }

    //鄭强的邏輯
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法執行之前
        System.out.println("方法執行前："+method.getName()+" :傳遞的參數..."+ Arrays.toString(args));
        //方法執行
        Object invoke = method.invoke(obj, args);
        //方法執行后
        System.out.println("方法執行后："+obj);
        return invoke;
    }
}